#include"Common.h"
#include"MutexGuard.h"

template<class T>
class BlockQueue
{
public:
    //构造
    BlockQueue(int capacity = 5)
        :_capacity(capacity)
    {
        pthread_mutex_init(&_mtx, nullptr);
        pthread_cond_init(&_empty, nullptr);
        pthread_cond_init(&_full, nullptr);
    }
    //插入
    void push(const T& in)
    {
        MutexGuard mutexguard(&_mtx);
        while (isQueueFull()) pthread_cond_wait(&_full, &_mtx);
        _q.push(in);
        pthread_cond_signal(&_empty);
    }
    //删除
    void pop(T* out)
    {
        MutexGuard mutexguard(&_mtx);
        while(isQueueEmpty()) pthread_cond_wait(&_empty, &_mtx);
        *out = _q.front();
        _q.pop();
        pthread_cond_signal(&_full);
    }
    //析构
    ~BlockQueue()
    {
        pthread_mutex_destroy(&_mtx);
        pthread_cond_destroy(&_empty);
        pthread_cond_destroy(&_full);
    }
//////////////////////////////////////////////////
    bool isQueueEmpty()
    {
        return _q.empty();
    }
    bool isQueueFull()
    {
        return _q.size() == _capacity;
    }
private:
    std::queue<T> _q;
    int _capacity;//队列中元素的上限
    pthread_mutex_t _mtx;
    pthread_cond_t _empty; // 用它来表示队列是否空的条件
    pthread_cond_t _full;  //  用它来表示队列是否满的条件
};